package com.example.imoocmall.exception;

import com.example.imoocmall.common.ApiRestResponse;
import com.example.imoocmall.filter.WebLogAspect;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * 处理统一异常的handler
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private final org.slf4j.Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

//    @ExceptionHandler(Exception.class)
//    @ResponseBody
//    public Object handleException(Exception e){
//        log.error("Default Exception:",e);
//        return ApiRestResponse.error(ImoocMallExceptionEnum.SYSTEM_REEOR);
//    }

    @ExceptionHandler(ImoocMallException.class)
    @ResponseBody
    public Object handleImoocMallException(ImoocMallException e){
        log.error("ImoocMallException:",e);
        return ApiRestResponse.error(e.getCode(),e.getMessage());
    }
    /**
     * 将异常信息暴露给用户@valid
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    private ApiRestResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValidException:"+e);

        return handleBindingResult(e.getBindingResult());

    }

    private ApiRestResponse handleBindingResult(BindingResult result){
        //把异常处理为对外暴露的提示
        List<String> list = new ArrayList<>();
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError objectError : allErrors){
                String message= objectError.getDefaultMessage();
                list.add(message);
            }
        }
        if (list.size() == 0){
            return ApiRestResponse.error(ImoocMallExceptionEnum.REQUEST_ARGUMENT_ERROR);
        }
        return ApiRestResponse.error(ImoocMallExceptionEnum.REQUEST_ARGUMENT_ERROR.getCode(),list.toString());
    }
}
